package com.iot.manager.ui.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.chip.Chip;
import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.network.WebSocketManager;

import java.util.ArrayList;
import java.util.List;

public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.DeviceViewHolder>
        implements WebSocketManager.DeviceStatusListener, WebSocketManager.DeviceDataListener {
    
    private List<Device> devices = new ArrayList<>();
    private OnDeviceClickListener listener;
    private Context context;

    public interface OnDeviceClickListener {
        void onDeviceClick(Device device);
    }

    public DeviceAdapter(Context context, OnDeviceClickListener listener) {
        this.context = context;
        this.listener = listener;
        WebSocketManager.getInstance(context).addStatusListener(this);
        WebSocketManager.getInstance(context).addDataListener(this);
    }

    public void setDevices(List<Device> devices) {
        this.devices = devices;
        notifyDataSetChanged();
    }

    public void updateDeviceStatus(String deviceId, String status) {
        for (int i = 0; i < devices.size(); i++) {
            if (devices.get(i).getDeviceId().equals(deviceId)) {
                devices.get(i).setStatus(status);
                notifyItemChanged(i);
                break;
            }
        }
    }

    public void updateDeviceData(String deviceId, Double temperature, Double humidity) {
        for (int i = 0; i < devices.size(); i++) {
            if (devices.get(i).getDeviceId().equals(deviceId)) {
                Device device = devices.get(i);
                if (temperature != null) device.setTemperature(temperature);
                if (humidity != null) device.setHumidity(humidity);
                notifyItemChanged(i);
                break;
            }
        }
    }

    @Override
    public void onDeviceStatusChanged(String deviceId, String status, String lastHeartbeat) {
        updateDeviceStatus(deviceId, status);
    }

    @Override
    public void onDeviceDataUpdated(String deviceId, Double temperature, Double humidity) {
        updateDeviceData(deviceId, temperature, humidity);
    }

    @NonNull
    @Override
    public DeviceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_device, parent, false);
        return new DeviceViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DeviceViewHolder holder, int position) {
        Device device = devices.get(position);
        holder.bind(device);
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    public void onDestroy() {
        WebSocketManager.getInstance(context).removeStatusListener(this);
        WebSocketManager.getInstance(context).removeDataListener(this);
    }

    class DeviceViewHolder extends RecyclerView.ViewHolder {
        private TextView tvDeviceName;
        private TextView tvDeviceId;
        private Chip chipStatus;
        private TextView tvTemperature;
        private TextView tvHumidity;

        DeviceViewHolder(@NonNull View itemView) {
            super(itemView);
            tvDeviceName = itemView.findViewById(R.id.tv_device_name);
            tvDeviceId = itemView.findViewById(R.id.tv_device_id);
            chipStatus = itemView.findViewById(R.id.chip_status);
            tvTemperature = itemView.findViewById(R.id.tv_temperature);
            tvHumidity = itemView.findViewById(R.id.tv_humidity);

            itemView.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    listener.onDeviceClick(devices.get(position));
                }
            });
        }

        void bind(Device device) {
            tvDeviceName.setText(device.getName());
            tvDeviceId.setText("设备ID: " + device.getDeviceId());
            chipStatus.setText(device.getStatus().equals("online") ? "在线" : "离线");
            chipStatus.setChipBackgroundColorResource(
                device.getStatus().equals("online") ? R.color.online : R.color.offline
            );

            if (device.getTemperature() != null) {
                tvTemperature.setText(String.format("%.1f°C", device.getTemperature()));
            } else {
                tvTemperature.setText("-");
            }

            if (device.getHumidity() != null) {
                tvHumidity.setText(String.format("%.1f%%", device.getHumidity()));
            } else {
                tvHumidity.setText("-");
            }
        }
    }
} 